/**
 * UI管理
 */
const UI = {
    /**
     * 初始化UI
     */
    initialize() {
        // 初始化事件监听器
        this.setupEventListeners();
        
        // 更新游戏信息显示
        this.updateGameInfo();
        
        // 更新资源概览
        this.updateResourcesOverview();
    },
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 时间控制按钮
        document.getElementById('pause-btn').addEventListener('click', () => {
            Game.setSpeed(CONFIG.GAME_SPEED.PAUSED);
        });
        
        document.getElementById('speed-1').addEventListener('click', () => {
            Game.setSpeed(CONFIG.GAME_SPEED.SLOW);
        });
        
        document.getElementById('speed-10').addEventListener('click', () => {
            Game.setSpeed(CONFIG.GAME_SPEED.MEDIUM);
        });
        
        document.getElementById('speed-100').addEventListener('click', () => {
            Game.setSpeed(CONFIG.GAME_SPEED.FAST);
        });
        
        // 强者榜按钮
        document.getElementById('strongest-btn').addEventListener('click', () => {
            this.showStrongestPanel();
        });
        
        // 魔王挑战关闭按钮
        document.getElementById('boss-close').addEventListener('click', () => {
            this.hideBossChallenge();
        });
        
        // 强者榜关闭按钮
        document.getElementById('strongest-close').addEventListener('click', () => {
            this.hideStrongestPanel();
        });
        
        // 保存按钮
        document.getElementById('save-btn').addEventListener('click', () => {
            this.showSaveDialog();
        });
        
        // 加载按钮
        document.getElementById('load-btn').addEventListener('click', () => {
            this.showLoadDialog();
        });
        
        // 关闭弹窗按钮
        document.getElementById('modal-close').addEventListener('click', () => {
            this.hideModal();
        });
        
        // 王国详情操作按钮
        document.getElementById('develop-economy').addEventListener('click', () => {
            const kingdomId = document.getElementById('kingdom-detail').dataset.kingdomId;
            const kingdom = GameData.kingdoms.find(k => k.id === kingdomId);
            if (kingdom) {
                KingdomSystem.developEconomy(kingdom);
                this.updateKingdomDetail(kingdom);
                this.updateResourcesOverview();
            }
        });
        
        document.getElementById('expand-military').addEventListener('click', () => {
            const kingdomId = document.getElementById('kingdom-detail').dataset.kingdomId;
            const kingdom = GameData.kingdoms.find(k => k.id === kingdomId);
            if (kingdom) {
                KingdomSystem.expandMilitary(kingdom);
                this.updateKingdomDetail(kingdom);
                this.updateResourcesOverview();
            }
        });
        
        document.getElementById('explore-resources').addEventListener('click', () => {
            const kingdomId = document.getElementById('kingdom-detail').dataset.kingdomId;
            const kingdom = GameData.kingdoms.find(k => k.id === kingdomId);
            if (kingdom) {
                KingdomSystem.exploreResources(kingdom);
                this.updateKingdomDetail(kingdom);
                this.updateResourcesOverview();
                MapRenderer.render();
            }
        });
        
        // 魔王挑战按钮
        document.getElementById('start-challenge').addEventListener('click', () => {
            const victory = EventSystem.executeBossChallenge();
            this.hideBossChallenge();
            
            // 显示结果弹窗
            this.showBattleResult(victory);
            
            // 更新游戏信息
            this.updateGameInfo();
            this.updateResourcesOverview();
        });
        
        // 标签页切换
        const tabs = document.querySelectorAll('.tab');
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabName = tab.dataset.tab;
                
                // 切换标签页激活状态
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                
                // 切换内容显示
                const tabContents = document.querySelectorAll('.tab-content');
                tabContents.forEach(content => content.classList.remove('active'));
                document.getElementById(`${tabName}-list`).classList.add('active');
                
                // 如果是历史强者标签，加载历史数据
                if (tabName === 'history') {
                    this.loadHistoricalHeroes();
                }
            });
        });
    },
    
    /**
     * 更新游戏信息显示
     */
    updateGameInfo() {
        document.getElementById('current-year').textContent = GameData.gameState.currentYear;
        document.getElementById('boss-countdown').textContent = GameData.gameState.bossCountdown;
        
        // 更新时间控制按钮状态
        const speedButtons = {
            [CONFIG.GAME_SPEED.PAUSED]: 'pause-btn',
            [CONFIG.GAME_SPEED.SLOW]: 'speed-1',
            [CONFIG.GAME_SPEED.MEDIUM]: 'speed-10',
            [CONFIG.GAME_SPEED.FAST]: 'speed-100'
        };
        
        Object.entries(speedButtons).forEach(([speed, id]) => {
            const button = document.getElementById(id);
            if (parseInt(speed) === GameData.gameState.gameSpeed) {
                button.classList.add('active');
            } else {
                button.classList.remove('active');
            }
        });
        
        // 更新魔王倒计时警告
        const bossCountdownElement = document.getElementById('boss-countdown');
        if (GameData.gameState.bossCountdown <= CONFIG.BOSS.WARNING_YEARS) {
            bossCountdownElement.classList.add('warning');
        } else {
            bossCountdownElement.classList.remove('warning');
        }
    },
    
    /**
     * 更新位面和魔王信息
     */
    updatePlaneBossInfo() {
        const infoElement = document.getElementById('plane-boss-info');
        const titleElement = document.getElementById('plane-boss-title');
        if (infoElement) {
            infoElement.textContent = `当前位面：第${GameData.gameState.currentPlane}位面 | 魔王：${GameData.boss.name} | 战力：${GameData.boss.power}`;
        }
        if (titleElement) {
            titleElement.textContent = `[${GameData.gameState.currentYear}年] 当前位面：第${GameData.gameState.currentPlane}位面，魔王名称：${GameData.boss.name}`;
        }
    },
    
    /**
     * 更新资源概览
     */
    updateResourcesOverview() {
        const overview = GameData.getOverviewData();
        
        document.getElementById('total-population').textContent = Utils.formatNumber(overview.totalPopulation);
        document.getElementById('total-resources').textContent = Utils.formatNumber(overview.totalResources);
        document.getElementById('total-military').textContent = Utils.formatNumber(overview.totalMilitary);
        document.getElementById('total-heroes').textContent = Utils.formatNumber(overview.totalHeroes);
    },
    
    /**
     * 显示王国详情
     * @param {Object} kingdom - 王国对象
     */
    showKingdomDetail(kingdom) {
        const detailPanel = document.getElementById('kingdom-detail');
        
        // 存储王国ID
        detailPanel.dataset.kingdomId = kingdom.id;
        
        // 更新详情内容
        this.updateKingdomDetail(kingdom);
        
        // 显示详情面板
        detailPanel.classList.remove('hidden');
    },
    
    /**
     * 更新王国详情内容
     * @param {Object} kingdom - 王国对象
     */
    updateKingdomDetail(kingdom) {
        const race = GameData.getRaceById(kingdom.raceId);
        
        document.getElementById('kingdom-name').textContent = kingdom.name;
        document.getElementById('kingdom-race').textContent = race ? race.name : "未知种族";
        document.getElementById('kingdom-founded').textContent = kingdom.foundYear;
        document.getElementById('kingdom-population').textContent = Utils.formatNumber(kingdom.population);
        document.getElementById('kingdom-resources').textContent = Utils.formatNumber(kingdom.resources);
        document.getElementById('kingdom-military').textContent = Utils.formatNumber(kingdom.military);
        document.getElementById('kingdom-status').textContent = kingdom.status;
    },
    
    /**
     * 隐藏王国详情
     */
    hideKingdomDetail() {
        document.getElementById('kingdom-detail').classList.add('hidden');
    },
    
    /**
     * 显示强者榜面板
     */
    showStrongestPanel() {
        // 加载当前强者榜数据
        this.loadStrongestList();
        
        // 显示面板
        document.getElementById('strongest-panel').classList.remove('hidden');
    },
    
    /**
     * 隐藏强者榜面板
     */
    hideStrongestPanel() {
        document.getElementById('strongest-panel').classList.add('hidden');
    },
    
    /**
     * 加载当前强者榜数据
     */
    loadStrongestList() {
        const strongestList = NPCSystem.getStrongestListData();
        const listElement = document.getElementById('strongest-list');
        
        // 清空列表
        listElement.innerHTML = '';
        
        // 添加强者条目
        strongestList.forEach(hero => {
            const heroItem = document.createElement('div');
            heroItem.className = 'hero-item';
            
            heroItem.innerHTML = `
                <div class="hero-rank">${hero.rank}</div>
                <div class="hero-avatar">${hero.name.charAt(0)}</div>
                <div class="hero-info">
                    <div class="hero-name">${hero.name}</div>
                    <div>${hero.race} | ${hero.age}岁</div>
                </div>
                <div class="hero-ability">${hero.ability}</div>
                <div class="hero-status status-${hero.status === '存活' ? 'alive' : 'dead'}">${hero.status}</div>
            `;
            
            listElement.appendChild(heroItem);
        });
    },
    
    /**
     * 加载历史强者数据
     */
    loadHistoricalHeroes() {
        const historicalHeroes = NPCSystem.getHistoricalHeroesData();
        const listElement = document.getElementById('history-list');
        
        // 清空列表
        listElement.innerHTML = '';
        
        // 添加历史强者条目
        historicalHeroes
            .sort((a, b) => b.ability - a.ability)
            .slice(0, 100)
            .forEach((hero, index) => {
                const heroItem = document.createElement('div');
                heroItem.className = 'hero-item';
                
                heroItem.innerHTML = `
                    <div class="hero-rank">${index + 1}</div>
                    <div class="hero-avatar">${hero.name.charAt(0)}</div>
                    <div class="hero-info">
                        <div class="hero-name">${hero.name}</div>
                        <div>${hero.race} | ${hero.birthYear}-${hero.deathYear}（享年${hero.lifespan}岁）</div>
                    </div>
                    <div class="hero-ability">${hero.ability}</div>
                `;
            
            listElement.appendChild(heroItem);
        });
    },
    
    /**
     * 显示魔王挑战界面
     */
    showBossChallenge() {
        const bossPanel = document.getElementById('boss-challenge');
        
        // 更新魔王信息
        document.getElementById('boss-name').textContent = GameData.boss.name;
        document.getElementById('boss-ability').textContent = Utils.formatNumber(GameData.boss.ability);
        
        // 更新魔王头像
        document.getElementById('boss-image').src = GameData.boss.image;
        
        // 更新魔王弱点
        const weakness = GameData.boss.weakness;
        const weaknessRace = GameData.getRaceById(weakness.raceId);
        document.getElementById('boss-weakness').textContent = `对${weaknessRace.name}伤害${Math.round(weakness.effect * 100)}%`;
        
        // 更新战力对比
        const playerPower = EventSystem.calculatePlayerPower();
        document.getElementById('player-power').textContent = Utils.formatNumber(playerPower);
        document.getElementById('boss-power').textContent = Utils.formatNumber(GameData.boss.ability);
        
        // 更新进度条
        const maxPower = Math.max(playerPower, GameData.boss.ability);
        document.getElementById('player-power-bar').style.width = `${playerPower / maxPower * 100}%`;
        document.getElementById('boss-power-bar').style.width = `${GameData.boss.ability / maxPower * 100}%`;
        
        // 显示面板
        bossPanel.classList.remove('hidden');
    },
    
    /**
     * 隐藏魔王挑战界面
     */
    hideBossChallenge() {
        document.getElementById('boss-challenge').classList.add('hidden');
    },
    
    /**
     * 显示战斗结果
     * @param {boolean} victory - 是否胜利
     */
    showBattleResult(victory) {
        const modalBody = document.getElementById('modal-body');
        
        if (victory) {
            modalBody.innerHTML = `
                <h3 class="victory">胜利！</h3>
                <p>大陆联军成功击败了魔王"${GameData.boss.name}"！</p>
                <p>解锁新位面：第${GameData.gameState.currentPlane}位面</p>
                <button id="continue-btn">继续游戏</button>
            `;
        } else {
            modalBody.innerHTML = `
                <h3 class="defeat">失败！</h3>
                <p>大陆联军不敌魔王"${GameData.boss.name}"，遭受重创！</p>
                <p>魔王将在${GameData.gameState.bossCountdown}年后再次降临！</p>
                <button id="continue-btn">继续游戏</button>
            `;
        }
        
        // 添加继续按钮事件
        document.getElementById('continue-btn').addEventListener('click', () => {
            this.hideModal();
            Game.setSpeed(CONFIG.GAME_SPEED.SLOW);
        });
        
        this.showModal();
    },
    
    /**
     * 显示保存对话框
     */
    showSaveDialog() {
        const modalBody = document.getElementById('modal-body');
        
        // 获取现有存档
        const saveSlots = Utils.getSaveSlots();
        
        let saveSlotHtml = '';
        for (let i = 0; i < CONFIG.SAVE.MAX_MANUAL_SAVES; i++) {
            const slot = saveSlots.find(s => s.name === `manual_${i}`);
            
            if (slot) {
                const date = new Date(slot.timestamp);
                saveSlotHtml += `
                    <div class="save-slot">
                        <div class="slot-info">
                            <div>存档 ${i + 1}</div>
                            <div>年份: ${slot.year}</div>
                            <div>${date.toLocaleString()}</div>
                        </div>
                        <button class="save-btn" data-slot="manual_${i}">覆盖</button>
                    </div>
                `;
            } else {
                saveSlotHtml += `
                    <div class="save-slot">
                        <div class="slot-info">
                            <div>存档 ${i + 1}</div>
                            <div>空</div>
                        </div>
                        <button class="save-btn" data-slot="manual_${i}">保存</button>
                    </div>
                `;
            }
        }
        
        modalBody.innerHTML = `
            <h3>保存游戏</h3>
            <div class="save-slots">
                ${saveSlotHtml}
            </div>
        `;
        
        // 添加保存按钮事件
        const saveButtons = modalBody.querySelectorAll('.save-btn');
        saveButtons.forEach(button => {
            button.addEventListener('click', () => {
                const slotName = button.dataset.slot;
                if (GameData.saveGameState(slotName)) {
                    Utils.addLogEntry(`游戏已保存到存档${slotName.replace('manual_', '')}`, 'positive');
                    this.hideModal();
                } else {
                    Utils.addLogEntry(`保存游戏失败`, 'important');
                }
            });
        });
        
        this.showModal();
    },
    
    /**
     * 显示加载对话框
     */
    showLoadDialog() {
        const modalBody = document.getElementById('modal-body');
        
        // 获取现有存档
        const saveSlots = Utils.getSaveSlots();
        
        if (saveSlots.length === 0) {
            modalBody.innerHTML = `
                <h3>加载游戏</h3>
                <p>没有找到存档</p>
            `;
        } else {
            let saveSlotHtml = '';
            saveSlots.forEach(slot => {
                const date = new Date(slot.timestamp);
                saveSlotHtml += `
                    <div class="save-slot">
                        <div class="slot-info">
                            <div>存档 ${slot.name.replace('manual_', '')}</div>
                            <div>年份: ${slot.year}</div>
                            <div>${date.toLocaleString()}</div>
                        </div>
                        <button class="load-btn" data-slot="${slot.name}">加载</button>
                    </div>
                `;
            });
            
            modalBody.innerHTML = `
                <h3>加载游戏</h3>
                <div class="save-slots">
                    ${saveSlotHtml}
                </div>
            `;
            
            // 添加加载按钮事件
            const loadButtons = modalBody.querySelectorAll('.load-btn');
            loadButtons.forEach(button => {
                button.addEventListener('click', () => {
                    const slotName = button.dataset.slot;
                    if (GameData.loadGameState(slotName)) {
                        Utils.addLogEntry(`游戏已从存档${slotName.replace('manual_', '')}加载`, 'positive');
                        this.hideModal();
                        
                        // 更新UI
                        this.updateGameInfo();
                        this.updateResourcesOverview();
                        MapRenderer.render();
                        
                        // 暂停游戏
                        Game.setSpeed(CONFIG.GAME_SPEED.PAUSED);
                    } else {
                        Utils.addLogEntry(`加载游戏失败`, 'important');
                    }
                });
            });
        }
        
        this.showModal();
    },
    
    /**
     * 显示模态框
     */
    showModal() {
        document.getElementById('modal-container').classList.remove('hidden');
    },
    
    /**
     * 隐藏模态框
     */
    hideModal() {
        document.getElementById('modal-container').classList.add('hidden');
    }
};